import React from "react"
import {connect} from 'react-redux'
import {
  InputGroupAddon,
  InputGroup,
  Button,
  Modal,
  ModalHeader,
  ModalBody,
  ModalFooter,
  FormGroup,
  Label,
  Row,
  Col
} from "reactstrap"

import {CLEAR_FORM, SET_MODAL_DATA, SET_MODAL_STATUS} from '../../../redux/constants/projects'
import {
  createProject,
  updateProject,
  deleteProject,
  getSpotifyList,
  addUserToProject, deleteUserFromProject
} from '../../../redux/actions/projects'
import {setData, setNotification} from '../../../redux/actions/helper'
import {Check, Trash2} from "react-feather"
import "../../../assets/scss/components/reactstrap/modal/project-modal.scss"
import * as Yup from "yup";
import {Field, Formik, Form} from "formik";
import FullLoadingSpinner from "../../@vuexy/spinner/Full-loading-spinner";
import Select, {components} from "react-select";
import * as Icon from "react-feather";
import Checkbox from "../../@vuexy/checkbox/CheckboxesVuexy";
import {validateEmail} from "../../../helpers/utils";


const formSchema = Yup.object().shape({
  name: Yup.string().required("Обязательно"),
  link: Yup.string().required("Обязательно"),
})

class ProjectModal extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      name: "",
      link: "",
      spotify: "",
      description: "",
      user: ''
    }


    this.handleSubmit = this.handleSubmit.bind(this)
    this.toggleModal = this.toggleModal.bind(this)
    this.handleInputChange = this.handleInputChange.bind(this)
  }

  spotifyFilter = () => {
    return this.props.spotify_list.map(value => {
      return {
        ...value,
        value: value.id,
        artistId: value.id,
        label: value.name
      }
    })
  }

  addUser = () => {
    if (validateEmail(this.state.user)) {
      this.props.addUserToProject({project_id: this.props.projectId, email: this.state.user})
    } else {
      this.props.setNotification('Неверная почта!', "error")
    }
  }

  Option = props => {
    return (
      <components.Option {...props} >
        <div className='d-flex justify-content-start align-items-center'>
          <img width={24} height={24} src={props.data.image} alt=""/>
          <p className='m-0 ml-2'>{props.data.label}</p>
        </div>
      </components.Option>
    );
  };

  spotifyChange = (e) => {
    this.props.setData(SET_MODAL_DATA, {spotify: e})
  }

  searchSpotify = (e) => {
    this.props.getSpotifyList({name: e})
  }

  handleSubmit(e) {
    if (this.props.requestType === "update") {
      this.props.updateProject(e, this.props.projectId, this.props.requestParams)
    } else {
      this.props.createProject(e, this.props.requestParams)
    }

  }

  onInputChange = (inputValue, {action}) => {
    switch (action) {
      case 'input-change':
        this.searchSpotify(inputValue)
        return;
      default:
        return;
    }
  }

  filterOptions = () => {
    return true;
  };

  toggleModal = () => {
    this.props.setData(SET_MODAL_STATUS, false)
    this.props.setData(CLEAR_FORM)
  }

  handleInputChange(e) {
    this.props.setData(SET_MODAL_DATA, {[e.target.name]: e.target.value})
  }

  render() {
    return (
      <React.Fragment>
        <Modal
          isOpen={this.props.modal}
          toggle={this.toggleModal}
        >
          <ModalHeader toggle={this.toggleModal}>
            {this.props.requestType === "update" ? "Обновить проект" : "Новый проект"}
          </ModalHeader>

          <Formik
            enableReinitialize={true}
            initialValues={this.props.modalData}
            onSubmit={this.handleSubmit}
            validationSchema={formSchema}
          >
            {({errors, touched}) => (
              <Form className="project-modal-form">
                {this.props.spinner.includes('projects-create') && <FullLoadingSpinner/>}
                <ModalBody>
                  <FormGroup className="my-1">
                    <Label for="name" className="project-modal-label">Название проекта</Label>
                    <Field
                      type="text"
                      name="name"
                      id="name"
                      autoComplete="off"
                      placeholder="Название проекта"
                      onChange={this.handleInputChange}
                      value={this.props.modalData.name}
                      className={`form-control project-modal-input ${errors.name &&
                      touched.name &&
                      "is-invalid"}`}
                    />
                    {errors.name && touched.name ? (
                      <div className="invalid-tooltip">{errors.name}</div>
                    ) : null}
                  </FormGroup>

                  <FormGroup className="my-2">
                    <Label for="link" className="project-modal-label">Ссылка VK</Label>
                    <Field
                      type="text"
                      name="link"
                      id="link"
                      autoComplete="off"
                      placeholder="Ссылка VK"
                      onChange={this.handleInputChange}
                      value={this.props.modalData.link}
                      className={`form-control project-modal-input ${errors.link &&
                      touched.link &&
                      "is-invalid"}`}
                    />
                    {errors.link && touched.link ? (
                      <div className="invalid-tooltip">{errors.link}</div>
                    ) : null}
                  </FormGroup>

                  <FormGroup className="my-2">
                    <Label for="spotify" className="project-modal-label">Имя артиста на Spotify</Label>
                    <Select
                      className={``}
                      classNamePrefix="dark_select"
                      value={{
                        value: this.props.modalData.spotify.artistId || '',
                        label: this.props.modalData.spotify.name || ''
                      }}
                      options={this.spotifyFilter()}
                      isClearable={false}
                      onChange={this.spotifyChange}
                      name='typesList'
                      components={{Option: this.Option}}
                      onInputChange={this.onInputChange}
                      filterOption={this.filterOptions}
                    />
                    {errors.spotify && touched.spotify ? (
                      <div className="invalid-tooltip">{errors.spotify}</div>
                    ) : null}
                  </FormGroup>

                  <FormGroup className="my-2">
                    <Label for="description" className="project-modal-label">Описание</Label>
                    <Field
                      component="textarea"
                      rows="4"
                      name="description"
                      id="description"
                      autoComplete="off"
                      placeholder="Описание"
                      onChange={this.handleInputChange}
                      value={this.props.modalData.description || ''}
                      className="form-control project-modal-input project-modal-textarea"
                    />
                  </FormGroup>

                  {
                    this.props.requestType === "update" && <>
                      <h5 className='mt-2'>
                        <Icon.UserPlus size={20}/> Совместная работа
                      </h5>
                      <hr/>
                      <Row className='mb-1'>
                        <Col xs={12} sm={6}><span className='dark-grey'>Пользователь</span></Col>
                        <Col xs={12} sm={6} className='mt-1 mt-sm-0'>
                          <Row>
                            <Col xs={3}><Icon.Eye size={20}/></Col>
                            <Col xs={3}><Icon.Edit2 size={20}/></Col>
                            <Col xs={3}><Icon.DollarSign size={20}/></Col>
                            <Col xs={3}></Col>
                          </Row>
                        </Col>
                      </Row>
                      {
                        this.props.modalData.owners && this.props.modalData.owners.map(owner => {
                          return <Row key={owner.id} className='mt-1'>
                            <Col xs={12} sm={6}><Icon.User className='mr-1' size={20}/><span>{owner.email}</span></Col>
                            {owner.id !== this.props.modalData.owner.id &&
                            <Col xs={12} sm={6} className='mt-1 mt-sm-0'>
                              <Row>
                                <Col xs={3}>
                                  <Checkbox disabled color="primary" icon={<Check className="vx-icon" size={16}/>}
                                            defaultChecked={true}/>
                                </Col>
                                <Col xs={3}>
                                  <Checkbox disabled color="primary" icon={<Check className="vx-icon" size={16}/>}
                                            defaultChecked={true}/>
                                </Col>
                                <Col xs={3}>
                                  <Checkbox disabled color="primary" icon={<Check className="vx-icon" size={16}/>}
                                            defaultChecked={true}/>
                                </Col>
                                <Col xs={3}><Icon.Trash2
                                  onClick={() => this.props.deleteUserFromProject(owner.id, {project_id: this.props.projectId})}
                                  className='danger cursor-pointer' size={20}/></Col>
                              </Row>
                            </Col>
                            }
                          </Row>
                        })
                      }

                      <h6 className='text-center mt-3'><span>пригласить</span></h6>
                      <InputGroup className="mb-2">
                        <Field
                          type="text"
                          name="user"
                          id="user"
                          autoComplete="off"
                          placeholder=""
                          onChange={e => this.setState({user: e.target.value})}
                          value={this.state.user}
                          className={`form-control project-modal-input`}
                        />
                        <InputGroupAddon addonType="append" className="button-append">
                          <Button.Ripple onClick={this.addUser} color="flat-primary">
                            <Icon.Plus size={20}/> добавить
                          </Button.Ripple>
                        </InputGroupAddon>
                      </InputGroup>
                    </>
                  }

                </ModalBody>
                <ModalFooter>
                  {
                    this.props.requestType === "update" &&
                    <Button.Ripple
                      color="danger"
                      onClick={() => this.props.deleteProject(this.props.projectId, this.props.requestParams)}
                      className="project-modal-button"
                    >
                      <Trash2 className="btn-icon" size={14}/>
                      Удалить
                    </Button.Ripple>
                  }
                  <Button.Ripple color="primary" type="submit" className="project-modal-button">
                    Сохранить
                  </Button.Ripple>
                </ModalFooter>
              </Form>
            )}
          </Formik>
        </Modal>
      </React.Fragment>
    )
  }
}

const mapStateToProps = state => {
  return {
    modal: state.projects.modal,
    modalData: state.projects.modalData,
    spinner: state.helper.spinner,
    requestParams: state.projects.requestParams,
    requestType: state.projects.requestType,
    projectId: state.projects.projectId,
    spotify_list: state.projects.spotify_list,
  }
}

export default connect(mapStateToProps, {
  setData,
  getSpotifyList,
  createProject,
  updateProject,
  deleteProject,
  setNotification,
  addUserToProject,
  deleteUserFromProject,
})(ProjectModal)
